package cc.mllt.demoaopmybatisauth.demos.web.service.impl;

import cc.mllt.demoaopmybatisauth.demos.web.mapper.DataPermissionRuleMapper;
import cc.mllt.demoaopmybatisauth.demos.web.model.dto.RuleQueryParam;
import cc.mllt.demoaopmybatisauth.demos.web.model.entity.DataPermissionRule;
import cc.mllt.demoaopmybatisauth.demos.web.service.DataPermissionRuleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class DataPermissionRuleServiceImpl extends ServiceImpl<DataPermissionRuleMapper, DataPermissionRule> implements DataPermissionRuleService {

    @Autowired
    DataPermissionRuleMapper ruleMapper;

    /**
     * 获取用户相关规则（个人 + 角色）
     * @param param 查询参数
     */
    @Override
    public List<DataPermissionRule> getRules(RuleQueryParam param) {
        QueryWrapper<DataPermissionRule> query = new QueryWrapper<>();

        // 组合查询条件
        query.lambda()
                // 基础条件：规则类型为个人或角色
                .and(wq -> wq
                        .eq(DataPermissionRule::getRuleTargetType, DataPermissionRule.RuleTargetType.个人)
                        .eq(DataPermissionRule::getRuleTargetId, param.getUid())
                        .or()
                        .eq(DataPermissionRule::getRuleTargetType, DataPermissionRule.RuleTargetType.角色)
                        .in(DataPermissionRule::getRuleTargetId, param.getRoleIds())
                )
                // 模块过滤（可选）
//                .eq(param.getModuleCode() != null, DataPermissionRule::getModuleCode, param.getModuleCode())
                // 状态过滤（根据业务需要）
                .eq(DataPermissionRule::getStatus, "正常")
                // 逻辑删除过滤（由 @TableLogic 自动处理）
                // 权重排序
                .orderByDesc(DataPermissionRule::getRuleWeight);// 依据权重排序
        return ruleMapper.selectList(query);
    }
}
